<?php
// $Id$

/**
 * Controller_Admin_Web 控制器
 */
class Controller_Admin_background extends Controller_Abstract {
	
	function actionIndex()
	{
		 $this->union_table = activecode::meta();
		 $this->lists();
	}
	

	function actionAdd() {
	    //设置要操作的表单，并设置自动插入方式
	    $this->union_table = activecode::meta ();
	    $handle = new helper_autoinsert ( $this->union_table );
	    $form = new Form_activecode_add ( url ( $this->_context->controller_name . '/' . $this->_context->action_name ) );
	    //这里面会自动将get方式获取的参数传递到表单里面去的
	    $result = $handle->add ( $form, 'id', $_GET );
	    if ($this->_context->isGET ()) {
	        //传递$form值
	        $this->_view ['form'] = $result;
	        $this->_viewname = '../form/add';
	    } else {
	        //记录日志
	        if(!$_POST['id'])	{
	            Syslog::logs ( '添加激活码,id :' . $handle->form_database_obj->id );
	        }else{
	            Syslog::logs ( '编辑激活码,id :' . $handle->form_database_obj->id );
	        }
	        if($handle->status=='success')
	            $this->_context->forwardUrl = url("activecode/index");
	        return call_user_func_array(array($this,$handle->status),array($result));
	    }
	     
	}
	 
	/**
	 * 删除激活码
	 */
	function actionDel() {
	     Syslog::logs("删除激活码，ID：".print_r($this->_context->ids,true));
	     $activecode = activecode::find(array('id'=>$this->_context->ids,'used'=>1))->getOne();
	     if($activecode->id()){
	         $this->error('包含已经使用的激活码');
	     }
	    $this->union_table = activecode::meta();
	     $this->delete(array('id'=>$this->_context->ids));
	  	    	  
	}
	/**
	 * 激活码导入
	 */
	function actionfileimport()
	{
	

	    if($this->_context->isGET())
	    {
	        
	        $apply_list = Acctuser::getbdlist();
	        $form = new Form_activecode_exp(url($this->_context->controller_name.'/'.$this->_context->action_name));
	        $form->element('bdid')->items = $apply_list;
	        
	        $this->_view['form'] = $form;
	        $this->_viewname = '../activecode/add';
	        
	    }else{

	        set_time_limit(300);
	        $userfile = isset($this->_context->codefile)?trim($this->_context->codefile):'';
	        $host = Helper_Common::getRequestHost();
	        $userfile = str_replace($host, '', $userfile);
	        $bdid = ($this->_context->bdid);
	        if($bdid == ''){
	            $this->error('报单中心必须选择');
	        }
	        $card = array();
	        if($bdid == 0 ){
	            $card['bdcenter_acctname'] = '平台';
	            $card['bdcenter_realname'] = '平台';
	            $card['applyid'] = time();
	        }else{
                $bdcenter = Acctuser::find('id = ? and is_bd = 1 and bd_status = 1',$bdid)->getOne();
               
                if($bdcenter->id()){
                    $card['bdcenter_realname'] = $bdcenter->realname;
                    $card['bdcenter_acctname'] = $bdcenter->acctname;
                    $card['applyid'] = time();
                }else{
                    $this->error('报单中心不存在');
                }
	        }
	        
	   
	        if (is_file($userfile))
	        {
	            $handle = fopen($userfile, 'r');
	            if($handle)
	            {
	                $split_char = ",";
	                $i = 0;
	                $ok = 0;
	                $no = 0;
	                $line_num = 0;
	                $err_line = '';
	                while (!feof($handle))
	                {
	                    $line_num +=1;
	                    $lineCard = fgets($handle,400);
	                    $Split_arr = explode($split_char, $lineCard);
	                    if(QValidator::validate_between(count($Split_arr), 0, 1))
	                    {
	                       // var_dump($Split_arr);
	                        if(strlen($Split_arr[0])>0  && $Split_arr[0] != " ")
	                        {
	                            $card['active_code'] = trim(trim($Split_arr[0],"\t"));
	                           // var_dump($card);die;
                                try {
                                    $vouch = new activecode($card);
                                   $vouch->save();
                                    $ok +=1;
                                } catch (Exception $e) {
                                    $err_line .= ','.$line_num;
                                }
	                            
	                        }else
	                        {
	                            $no +=1;
	                            $err_line .= ','.$line_num;
	                            continue;
	                        }
	                    }else
	                    {
	                        $no +=1;
	                        $err_line .= ','.$line_num;
	                        continue;
	                    }
	                }
	                fclose($handle);
	                //删除文件
	           //     Helper_Common::safeDelFile($userfile);
	                syslog::logs('导入激活码:'.$ok.'条数据');
	                return $this->success(sprintf('成功导入%d条记录，失败%d条，分别存在:%s',$ok,$no,$err_line));
	            }else
	            {
	                return $this->error('文件打开失败');
	            }
	        }else
	        {
	            return $this->error('文件不存在,请重新上传');
	        }
	    }
	}
	/**
	 * 划拨激活码
	 * 
	 */
	function actiontransfer(){
	    if($this->_context->isGET())
	    {
           $bdlist = Acctuser::getbdlisthuabo();
           $activecode_total =   activecode::find('bdcenter_acctname = ?','平台')->getCount('id');
           $this->_view['bdlist'] = $bdlist;
           $this->_view['total'] = $activecode_total;
	    }else{
	        $bdid = intval($this->_context->bdid);
	        $bdcenter = Acctuser::find('id = ? and is_bd = 1',$bdid)->getOne();
	        if(!$bdcenter->id()){
	            $this->error('请选择报单中心');
	        }
	        if($bdcenter->bd_status == 1){
	            $this->error('报单中心已经被锁定');
	        }
	        $num = intval($this->_context->num);
	        if($num == 0){
	            $this->error('划拨数量 必须大于0');
	        }
	        if($bdid == 0){
	            $this->error('请选择报单中心');
	        }
	        $activecode_total =   activecode::find('bdcenter_acctname = ?','平台')->getCount('id');
	        if($num > $activecode_total) {
	            $this->error('划拨数量必须小于总数量');
	        }
	        $activecode  = activecode::find('bdcenter_acctname = ?','')->order('id desc')->limit(0,$num)->getAll();
	        $sql1 = "select id from active_code where bdcenter_acctname = '平台' order by id desc limit 0,{$num}";
	        $codeupdate = 	QDB::getConn()->execute($sql1)->fetchAll();
	        
	        if(count($codeupdate)){
	            $codeupdate = Helper_Array::toHashmap($codeupdate, 'id','id');
	            $codeupdatestr = join(',', $codeupdate);
	            $sql  = "update active_code set bdcenter_acctname = ?,bdcenter_realname = ? where id in ({$codeupdatestr})";
	            QDB::getConn()->execute($sql,array($bdcenter->acctname,$bdcenter->realname));
	            syslog::logs('划拨给'.$bdid.'报单中心'.$num.'条激活码');
	            $this->success('划拨成功');
	        }else{
	            $this->error('未找到可以划拨的激活码');
	        } 
	    }
	}
}


